package cn.edu.swust.adressbook.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.HashMap;
import java.util.Map;

import cn.edu.swust.adressbook.R;
import cn.edu.swust.adressbook.bean.Contact;
import cn.edu.swust.adressbook.service.IBaseService;
import cn.edu.swust.adressbook.service.impl.ContactServiceImpl;


public class DetailsActivity extends Activity implements View.OnClickListener{

    private ViewGroup mBack_btn;
    private TextView mEdit_btn;
    private PopupWindow mPopWindow;          ///< 二维码的浮框
    private TextView mPeople_name;
    private TextView mPhone_num;
    private ImageView mEr_wei_ma;
    private TextView mAddress;
    private ImageView mCall_btn;
    private ImageView mPush_msg;
    private TextView mCancle_toggle_btn;
    private TextView mCall_list;
    private TextView mPost_people;
    private String mPhoneNum;
    private Contact mContact;
    private IBaseService mContactService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        init();
    }



    // 初始化基本数据
    protected void init() {
        mContactService = new ContactServiceImpl(this);
        initControl();
        initIntent();
    }

    //找出要用的控件，绑定监听事件
    protected  void initControl()
    {
        mBack_btn = (ViewGroup) findViewById(R.id.back_btn);
        mBack_btn.setOnClickListener(this);
        mEdit_btn = (TextView) findViewById(R.id.edit_btn);
        mEdit_btn.setOnClickListener(this);
        mPeople_name = (TextView) findViewById(R.id.peopel_name);
        mPhone_num = (TextView) findViewById(R.id.phone_num);
        mAddress = (TextView) findViewById(R.id.address);
        mCall_btn = (ImageView) findViewById(R.id.call_btn);
        mCall_btn.setOnClickListener(this);
        mPush_msg = (ImageView) findViewById(R.id.meg_btn);
        mPush_msg.setOnClickListener(this);
        mCancle_toggle_btn = (TextView) findViewById(R.id.cancle_toggle);
        mCancle_toggle_btn.setOnClickListener(this);
        mCall_list = (TextView) findViewById(R.id.call_list);
        mCall_list.setOnClickListener(this);
        mPost_people = (TextView) findViewById(R.id.post_people);
        mPost_people.setOnClickListener(this);
        findViewById(R.id.image_code).setOnClickListener(this);
    }

    //获取Intent,初始化页面数据
    protected void initIntent()
    {
        //获取Intent
        Intent intent = getIntent();
        if(intent == null)
        {
            Toast.makeText(DetailsActivity.this,"获取联系人失败",Toast.LENGTH_SHORT).show();
            finish();
        }
        //获取传送的对象
        mContact = (Contact)intent.getSerializableExtra(MainActivity.PERSON);
        if (mContact != null){
            initViewData();
        }



    }

    private void initViewData() {
        //填充页面数据
        mPeople_name.setText(mContact.getName());
        mPhone_num.setText(mContact.getPhoneNumber());
        mAddress.setText(mContact.getPlaceOfCall());

        //获取电话
        mPhoneNum = mContact.getPhoneNumber();
    }

    //各个部分的点击逻辑
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_btn:
                finish();
                break;
            case R.id.edit_btn:
                Intent intent = new Intent(DetailsActivity.this,EditActivity.class);
                intent.putExtra(MainActivity.PERSON,mContact);
                startActivity(intent);
                break;
            case R.id.cancle_toggle:
                Toast.makeText(DetailsActivity.this,"dsadsa",Toast.LENGTH_SHORT).show();
                break;
            case R.id.call_list:
                break;
            case R.id.call_btn:
                call();
                break;
            case R.id.meg_btn:
                sendMessage();
                break;
            case R.id.image_code:
                showPopupWindow();
                break;
            default:
                break;
        }
    }

    //拨打电话
    private void call(){
        if(mPhoneNum != null){
            Toast.makeText(DetailsActivity.this,"dsadsa",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + mPhoneNum);
            intent.setData(data);
            startActivity(intent);
        }
    }

    //发送短信
    public void sendMessage(){
        if(mPhoneNum != null){
            Uri uri=Uri.parse("smsto://" + mPhoneNum); //要发送短信的电话号码
            Intent intent=new Intent(Intent.ACTION_SENDTO, uri);
            intent.putExtra(" "," ");
            startActivity(intent);
        }
    }

    /**
     * 选择群组的浮框
     */
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(DetailsActivity.this).inflate(R.layout.activity_qrcode, null);
        mPopWindow = new PopupWindow(contentView,
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setOutsideTouchable(true);
        ImageView imageView = (ImageView) contentView.findViewById(R.id.iv);
        imageView.setImageBitmap(generateBitmap());
        //显示PopupWindow
        View rootView = LayoutInflater.from(DetailsActivity.this).inflate(R.layout.activity_group_list, null);
        mPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);

    }

    /**
     * 生成具体的二维码
     * @return 二维码
     */
    private Bitmap generateBitmap() {
        String content = "";
        if (mContact != null){
            content = "姓名：" + mContact.getName() + "; 电话" + mContact.getPhoneNumber() ;
        }

        int width = 256;
        int height = 256;
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mContactService = new ContactServiceImpl(this);
        mContact = (Contact) mContactService.get(mContact.getId());
        if(mContact != null){

            initViewData();
        } else {
            finish();
        }
    }
}
